package org.example;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 负载均衡算法 --- 加权轮训算法
 * @author shenguangyang
 */
public class LbRoundRobinWeight extends LoadBalance {
    static Random random = new Random();
    private final AtomicInteger pos = new AtomicInteger(0);
    public static void main(String[] args) {
        LoadBalance loadBalance = new LbRoundRobinWeight();
        loadBalance.printf();
    }
    @Override
    public String getServer() {
        // =========================> 坐标轴方案
        /*
         * A: 5
         * B: 3
         * C: 2
         * weight: 0 ----- 5 --- 8 -- 10
         *                 A     B    C
         * eg: offset = 7
         * 循环1: offset > 5; offset = offset - 5; (offset = 2)
         * 循环2: offset < 3; return B;
         */
        int totalWeight = 0;
        for (Integer weight : ServerIps.WEIGHT_LIST.values()) {
            totalWeight += weight;
        }

        int offset = pos.getAndIncrement() % totalWeight;
        for (String ip : ServerIps.WEIGHT_LIST.keySet()) {
            Integer weight = ServerIps.WEIGHT_LIST.get(ip);
            // 假如此时权重轴是 0 ----- 5 --- 8 -- 10, offset = 7; weight = 5
            if (offset < weight) {
                return ip;
            }
            // 相当于权重轴变成了 0 --- 3 ----- 5
            offset = offset - weight;
        }
        return ServerIps.LIST.get(pos.get());
    }
}
